×
☰ See All Chapters

Difference between String, StringBuilder and StringBuffer in Java

String

String is immutable, once created cannot be changed. The object created as a String is stored in the String Constant Pool. Every immutable object in Java is thread safe that implies String is also thread safe. String cannot be used by two threads simultaneously. String once assigned cannot be changed.

StringBuffer

StringBuffer is mutable means one can change the value of the object. The object created through StringBuffer is stored in the heap. Methods of StringBuffer and StringBuilder are same, but methods in StringBuffer are synchronized and thread safe. Due to this it does not allow two threads to simultaneously access the same method. Each method can be accessed by one thread at a time. As only one thread can access method at a time, other thread has to wait till the previous thread completes, this hits the performance. Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class. String Buffer can be converted to the string by using toString() method.

StringBuilder

StringBuilder is same as the StringBuffer, that is it stores the object in heap and it can also be modified. The main difference between the StringBuffer and StringBuilder is that StringBuilder is not thread safe. StringBuilder is fast because multiple threads can simultaneously access the same methods.


All Chapters
Author